package com.easytouch.vmhdl.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.easytouch.core.DriverThread;
import com.easytouch.core.model.ColumnModel;
import com.easytouch.core.model.GoodsModel;
import com.easytouch.core.utils.Log;
import com.easytouch.core.utils.Tools;
import com.easytouch.vmhdl.AppApplication;
import com.easytouch.vmhdl.R;
import com.easytouch.vmhdl.activity.MainActivity;
import com.easytouch.vmhdl.view.HorizontalListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by gulin on 2017/12/1.
 */

public class GoodsFragment extends BaseFragment implements View.OnClickListener {

    private static final int FILTER_NONE = 0;
    private static final int FILTER_COLD = 1;
    private static final int FILTER_HOT = 2;

    private HorizontalListView mHl_goodslist_1;
    private HorizontalListView mHl_goodslist_2;
    private Timer timer;
    private ImageView mIv_arrow;

    private ArrayList<GoodsModel> goodsList1 = new ArrayList<>();
    private ArrayList<GoodsModel> goodsList2 = new ArrayList<>();
    MyAdapter myAdapter1;
    MyAdapter myAdapter2;

    private int mDuration = 60; // 倒计时
    private static final int COUNT_DOWN = 60;

    private Log mLogger = new Log("GoodsFragment.txt");

    private MyHandler mHandler;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_goods, container, false);

        showTop();
        showBottom(true, true);

        mHl_goodslist_1 = (HorizontalListView) view.findViewById(R.id.hl_goodslist_1);
        mHl_goodslist_1.setLongClickable(true);
        mHl_goodslist_2 = (HorizontalListView) view.findViewById(R.id.hl_goodslist_2);
        mHl_goodslist_2.setLongClickable(true);
        mIv_arrow = (ImageView) view.findViewById(R.id.iv_arrow);
        animation(mIv_arrow);//设置动画
        mIv_arrow.setOnClickListener(this);

        getAllGoods(FILTER_NONE);

        myAdapter1 = new MyAdapter(getActivity(), 0);
        myAdapter2 = new MyAdapter(getActivity(), 1);
        mHl_goodslist_1.setAdapter(myAdapter1);
        mHl_goodslist_2.setAdapter(myAdapter2);
        if(myAdapter2.getCount() > 7) {
            mHl_goodslist_2.scrollTo(myAdapter2.getCount() * 364);
        }
        mHl_goodslist_1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(position >= goodsList1.size())
                {
                    return;
                }
                GoodsModel goods = goodsList1.get(position);
                if(!goods.isGoodsHaveStock())
                {
                    return;
                }
                Bundle bundle = new Bundle();
                bundle.putString(PayFragment.PARAM_GOODS, goods.toString());
                bundle.putBoolean(PayFragment.PARAM_IS_LIST, true);
                goToFragment(MainActivity.FRAGMENT_PAY, bundle);
            }
        });
        mHl_goodslist_2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(position >= goodsList2.size())
                {
                    return;
                }
                GoodsModel goods = goodsList2.get(position);
                if(!goods.isGoodsHaveStock())
                {
                    return;
                }
                Bundle bundle = new Bundle();
                bundle.putString(PayFragment.PARAM_GOODS, goods.toString());
                bundle.putBoolean(PayFragment.PARAM_IS_LIST, true);
                goToFragment(MainActivity.FRAGMENT_PAY, bundle);
            }
        });

        timer = new Timer();
        timer.schedule(new ScrollTask(), 200, 200);

        mHandler = new MyHandler(this);
        mHandler.sendEmptyMessage(0);
        return view;
    }

    /**
     * 动画
     *
     * @param img
     */
    private void animation(ImageView img) {
        AnimationSet animationSet = new AnimationSet(true);
        //fromXDelta,  toXDelta,  fromYDelta,  toYDelta
        TranslateAnimation translateAnimation = new TranslateAnimation(0, -20, 0, 0);
        translateAnimation.setDuration(1000);
        translateAnimation.setRepeatCount(-1);               //设置重复次数
        translateAnimation.setRepeatMode(Animation.REVERSE);    //重新从头执行
        animationSet.addAnimation(translateAnimation);
        img.setAnimation(animationSet);
    }

    private void getAllGoods(final int filter)
    {
        ArrayList<GoodsModel> goodsList = new ArrayList<>();
        //mLogger.i("filter:" + String.valueOf(filter));
        //get all goods
        for(int i = 0;i < 5;i++) {
            String json = DriverThread.getInstance().getGoodsByCategory(i + 1, true);
            if(json == null || "".equals(json))
            {
                continue;
            }
            try {
                JSONObject object = new JSONObject(json);
                JSONArray data = object.getJSONArray("data");
                if(data == null || data.length() == 0)
                {
                    continue;
                }
                for (int j = 0;j < data.length();j++) {
                    JSONObject obj = data.getJSONObject(j);
                    GoodsModel model = GoodsModel.fromJson(obj);
                    //mLogger.i("goods:" + model.getCode() + " temp:" + model.getTemperatureState());
                    if(filter == FILTER_COLD)
                    {
                        if(model.getTemperatureState() == ColumnModel.TEMPERATURE_COLD)
                        {
                            goodsList.add(model);
                        }
                    }
                    else if(filter == FILTER_HOT)
                    {
                        if(model.getTemperatureState() == ColumnModel.TEMPERATURE_HEAT)
                        {
                            goodsList.add(model);
                        }
                    }
                    else {
                        goodsList.add(model);
                    }
                }
            } catch (JSONException e) {
                continue;
            }
        }
        //goodsList = goodsList.stream().filter(goods -> goods.getTemperatureState() == ColumnModel.TEMPERATURE_COLD).collect(Collectors.toList());
        goodsList1.clear();
        goodsList2.clear();
        int len = goodsList.size();
        if(len == 0)
        {
            return;
        }
        if(len <= 14)
        {
            for (int i = 0; i < goodsList.size(); i++) {
                if(i < 7)
                {
                    goodsList1.add(goodsList.get(i));
                }
                else
                {
                    goodsList2.add(goodsList.get(i));
                }
            }
        }
        else
        {
            int half = len / 2;
            for (int i = 0; i < goodsList.size(); i++) {
                if(i < half)
                {
                    goodsList1.add(goodsList.get(i));
                }
                else
                {
                    goodsList2.add(goodsList.get(i));
                }
            }
        }
    }

    public void setImage(ImageView imageView, String imageName) {

        mImageLoader.displayImage("file://" + AppApplication.path + "/images/goods_image/" + imageName, imageView, options, mLoadingListener);
    }

    /**
     * 重设倒计时
     */
    public void resetCountDown(int time)
    {
        if (time > 0)
            mDuration = time;
    }

    class ScrollTask extends TimerTask {

        private static final int MOVE_DIR_TO_RIGHT = 0;
        private static final int MOVE_DIR_TO_LEFT = 1;

        private int dir1 = MOVE_DIR_TO_RIGHT;
        private int dir2 = MOVE_DIR_TO_LEFT;

        private int x1 = -1;
        private int x2 = -1;

        @Override
        public void run() {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if(mHl_goodslist_1.getAdapter().getCount() > 7) {
                        int x = mHl_goodslist_1.getCurX();
                        //mLogger.i("ScrollX:" + String.valueOf(x));
                        boolean isNeedMove = true;
                        if(x1 == -1)
                        {
                            isNeedMove = true;
                            x1 = x;
                        }
                        else
                        {
                            if(x1 != x)
                            {
                                isNeedMove = true;
                                x1 = x;
                            }
                            else
                            {
                                isNeedMove = false;
                                //改变方向
                                if(dir1 == MOVE_DIR_TO_RIGHT)
                                {
                                    dir1 = MOVE_DIR_TO_LEFT;
                                }
                                else
                                {
                                    dir1 = MOVE_DIR_TO_RIGHT;
                                }
                                x1 = -1;
                            }
                        }
                        if(isNeedMove)
                        {
                            if(dir1 == MOVE_DIR_TO_RIGHT)
                            {
                                mHl_goodslist_1.move(200);
                            }
                            else if(dir1 == MOVE_DIR_TO_LEFT)
                            {
                                mHl_goodslist_1.move(-200);
                            }
                        }
                    }
                    if(mHl_goodslist_2.getAdapter().getCount() > 7) {
                        int x = mHl_goodslist_2.getCurX();
                        boolean isNeedMove = true;
                        if(x2 == -1)
                        {
                            isNeedMove = true;
                            x2 = x;
                        }
                        else
                        {
                            if(x2 != x)
                            {
                                isNeedMove = true;
                                x2 = x;
                            }
                            else
                            {
                                isNeedMove = false;
                                //改变方向
                                if(dir2 == MOVE_DIR_TO_RIGHT)
                                {
                                    dir2 = MOVE_DIR_TO_LEFT;
                                }
                                else
                                {
                                    dir2 = MOVE_DIR_TO_RIGHT;
                                }
                                x2 = -1;
                            }
                        }
                        if(isNeedMove)
                        {
                            if(dir2 == MOVE_DIR_TO_RIGHT)
                            {
                                mHl_goodslist_2.move(200);
                            }
                            else if(dir2 == MOVE_DIR_TO_LEFT)
                            {
                                mHl_goodslist_2.move(-200);
                            }
                        }
                    }
                }
            });

        }
    }

    @Override
    public void onDestroyView() {
        if(timer != null)
        {
            timer.cancel();
            timer = null;
        }
        if(mHandler != null)
        {
            mHandler.removeMessages(0);
        }
        super.onDestroyView();
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id)
        {
            case R.id.iv_arrow:
                goToFragment(MainActivity.FRAGMENT_LIST, null);
                break;
        }
    }

    @Override
    public void onBackButtonPressed() {
        super.onBackButtonPressed();
        goToFragment(MainActivity.FRAGMENT_HOME, null);
    }

    @Override
    public void onMenuPressed(final int type)
    {
        super.onMenuPressed(type);
        resetCountDown(COUNT_DOWN);
        timer.cancel();
        switch (type)
        {
            case BaseFragment.MENU_COOL:
                getAllGoods(FILTER_COLD);
                myAdapter1.notifyDataSetChanged();
                myAdapter2.notifyDataSetChanged();
                break;
            case BaseFragment.MENU_ALL:
                getAllGoods(FILTER_NONE);
                myAdapter1.notifyDataSetChanged();
                myAdapter2.notifyDataSetChanged();
                break;
            case BaseFragment.MENU_HOT:
                getAllGoods(FILTER_HOT);
                myAdapter1.notifyDataSetChanged();
                myAdapter2.notifyDataSetChanged();
                break;
        }
        mHl_goodslist_1.reset();//scrollTo(0);
        if(myAdapter2.getCount() > 7) {
            mHl_goodslist_2.scrollTo(myAdapter2.getCount() * 364);
        }
        else
        {
            mHl_goodslist_2.reset();
        }
        timer = null;
        timer = new Timer();
        timer.schedule(new ScrollTask(), 200, 200);
    }

    static class MyHandler extends Handler
    {

        private SoftReference<GoodsFragment> mFragment;

        public MyHandler(GoodsFragment fragment)
        {
            mFragment = new SoftReference<GoodsFragment>(fragment);
        }

        @Override
        public void handleMessage(Message msg)
        {
            super.handleMessage(msg);
            if(mFragment == null || mFragment.get() == null)
            {
                return;
            }
            switch (msg.what)
            {
                case 0: //倒计时
                {
                    int duration = mFragment.get().mDuration;
                    if(duration <= 0)
                    {
                        mFragment.get().goToFragment(MainActivity.FRAGMENT_HOME, null);
                    }
                    else
                    {
                        mFragment.get().mDuration--;
                        sendEmptyMessageDelayed(0, 1000);
                    }
                    break;
                }
            }
        }
    }

    class MyAdapter extends BaseAdapter {

        private ViewHolder holder;
        private Context mContext;
        private int mWhich = 0;

        public MyAdapter(Context context, final int which) {
            mContext = context;
            mWhich = which;
        }

        @Override
        public int getCount() {
            return mWhich == 0 ? goodsList1.size() : goodsList2.size();
        }

        @Override
        public Object getItem(int i) {
            return mWhich == 0 ? goodsList1.get(i) : goodsList2.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = View.inflate(mContext, R.layout.item_horizontal_list, null);
                holder = new ViewHolder();
                holder.list_item_bg = convertView.findViewById(R.id.list_item_bg);
                holder.iv_item_light = convertView.findViewById(R.id.iv_item_light);
                holder.iv_money = convertView.findViewById(R.id.iv_money);
                holder.tv_goods_price = convertView.findViewById(R.id.tv_goods_price);
                holder.iv_item_goods = convertView.findViewById(R.id.iv_item_goods);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            final GoodsModel goods = (mWhich == 0 ? goodsList1.get(position) : goodsList2.get(position));
            //商品图片
            setImage(holder.iv_item_goods, String.valueOf(goods.getCode()) + "/0.png");
            //是否无货
            if(goods.isGoodsHaveStock())
            {
                holder.list_item_bg.setVisibility(View.VISIBLE);
                holder.iv_money.setVisibility(View.VISIBLE);
                //价格
                String price = Tools.priceFormat(String.valueOf(goods.getPrice()));
                holder.tv_goods_price.setText(price);
                holder.iv_item_goods.setAlpha(1.0f);
                switch (goods.getTemperatureState())
                {
                    case ColumnModel.TEMPERATURE_COLD:
                        holder.iv_item_light.setBackgroundResource(R.drawable.goodslist_light_cool);
                        break;
                    case ColumnModel.TEMPERATURE_HEAT:
                        holder.iv_item_light.setBackgroundResource(R.drawable.goodslist_light_hot);
                        break;
                    default:
                        holder.iv_item_light.setBackgroundResource(R.drawable.goodslist_light_normal);
                        break;
                }
                holder.iv_item_light.setVisibility(View.VISIBLE);
            }
            else
            {
                holder.list_item_bg.setVisibility(View.GONE);
                holder.iv_money.setVisibility(View.GONE);
                holder.tv_goods_price.setText(R.string.nostock);
                holder.iv_item_goods.setAlpha(0.6f);
                holder.iv_item_light.setVisibility(View.GONE);
            }

            return convertView;
        }

        class ViewHolder {
            ImageView list_item_bg;
            ImageView iv_item_light;
            ImageView iv_item_goods;
            ImageView iv_money;
            TextView tv_goods_price;
        }

    }
}
